<template>
  <el-dialog
    v-model="dialogVisible"
    title="管线绘制工具"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="pipe-drawing-dialog"
    append-to-body
  >
    <div class="pipe-drawing-container">
      <!-- 左侧Cesium地图 -->
      <div class="map-container">
        <div id="pipeDrawingContainer" ref="pipeDrawingContainer" style="width: 100%; height: 100%"></div>
        <!-- 地图图例 -->
        <div class="map-legend">
          <div class="legend-item">
            <div class="legend-color" style="background-color: lime"></div>
            <span>热力管线</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: blue"></div>
            <span>轨道交通</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: yellow"></div>
            <span>用户绘制</span>
          </div>
        </div>
        <!-- 地图控制按钮 -->
        <div class="map-controls">
          <el-button type="primary" :icon="isDrawing ? 'Close' : 'EditPen'" @click="toggleDrawing">
            {{ isDrawing ? '取消绘制' : '开始绘制' }}
          </el-button>
          <el-button v-if="isDrawing && currentPoints.length > 0" type="info" icon="Back" @click="handleUndoLastPoint">撤销</el-button>
          <el-button v-if="isDrawing && currentPoints.length >= 2" type="success" icon="Check" @click="handleFinishDrawing"> 完成绘制 </el-button>
          <el-button type="warning" icon="Delete" @click="handleClearAllPipes" :disabled="!hasPipes">清除所有</el-button>
        </div>
      </div>

      <!-- 右侧表单 -->
      <div class="form-container">
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>管线信息</span>
            </div>
          </template>

          <el-scrollbar height="600px" class="form-scrollbar">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="pipe-form">
              <!-- 管线基本信息 -->

              <el-form-item label="管径" prop="gj">
                <el-input type="number" v-model="formData.gj" placeholder="请输入管径" />
              </el-form-item>

              <el-form-item label="管龄" prop="gl">
                <el-input type="number" v-model="formData.gl" placeholder="请输入管龄" />
              </el-form-item>

              <el-form-item label="接口类型">
                <el-select v-model="formData.jklx" clearable placeholder="请选择接口类型">
                  <el-option v-for="item in riskModel['接口类型']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="管材">
                <el-select v-model="formData.gc" clearable placeholder="请选择管材">
                  <el-option v-for="item in riskModel['管材']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="管道位置">
                <el-select v-model="formData.gdwz" clearable placeholder="请选择管道位置">
                  <el-option v-for="item in riskModel['管道位置']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="管道压力">
                <el-select v-model="formData.gdyl" clearable placeholder="请选择管道压力">
                  <el-option v-for="item in riskModel['管道压力']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="管道深度">
                <el-input type="number" v-model="formData.gdsd" placeholder="请输入管道深度(m)" />
              </el-form-item>

              <el-form-item label="管道设计">
                <el-select v-model="formData.gdsj" clearable placeholder="请选择管道设计">
                  <el-option v-for="item in riskModel['管道设计']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="地质">
                <el-select v-model="formData.dz" multiple clearable placeholder="请选择地质类型">
                  <el-option v-for="item in riskModel['地质']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="周边施工数量" v-if="formData.dz">
                <el-input-number style="width: 100%" v-model="formData.dzsl" placeholder="请输入周边施工数量" />
              </el-form-item>

              <el-form-item label="施工破坏">
                <el-select v-model="formData.sgph" clearable placeholder="请选择施工破坏情况">
                  <el-option v-for="item in riskModel['施工破坏']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="气温">
                <el-input-number style="width: 100%" v-model="formData.qw" placeholder="请输入气温(℃)" />
              </el-form-item>

              <el-form-item label="气象">
                <el-select v-model="formData.qx" multiple clearable placeholder="请选择气象条件">
                  <el-option label="强降雨" value="强降雨" />
                  <el-option label="冰冻" value="冰冻" />
                </el-select>
              </el-form-item>

              <el-form-item label="自然灾害">
                <el-select v-model="formData.zrzh" clearable placeholder="请选择自然灾害类型">
                  <el-option v-for="item in riskModel['自然灾害']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="在线监测数据">
                <el-select v-model="formData.zxjcsj" clearable placeholder="请选择在线监测数据">
                  <el-option v-for="item in riskModel['在线监测数据']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="巡检频率">
                <el-select v-model="formData.xjpl" clearable placeholder="请选择巡检频率">
                  <el-option v-for="item in riskModel['巡检频率']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="监测预警">
                <el-select v-model="formData.jcyj" clearable placeholder="请选择监测预警">
                  <el-option v-for="item in riskModel['监测预警']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="泄漏记录">
                <el-select v-model="formData.xljl" clearable placeholder="请选择泄漏记录">
                  <el-option v-for="item in riskModel['泄漏记录']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item label="维修记录">
                <el-select v-model="formData.wxjl" clearable placeholder="请选择维修记录">
                  <el-option v-for="item in riskModel['维修记录']" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <!-- 操作按钮 -->
              <el-form-item>
                <el-button type="primary" icon="Upload" :loading="submitting" @click="submitPipeData" :disabled="!currentPipeData">
                  提交管线数据
                </el-button>
              </el-form-item>
            </el-form>
          </el-scrollbar>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import usePipeDrawing, { type PipeData, type PipePoint, type PipeRiskInfo } from '@/hooks/usePipeDrawing';
import { useCesiumMap } from '@/hooks/useCesiumMap';
import useDialog from '@/hooks/useDialog';
import { submitPipeData as submitPipeDataApi } from '@/api/pipeDrawing';
import { scoringCriteria } from '@/api/riskModel';

// 响应式数据
const pipeDrawingContainer = ref();
const formRef = ref();
const submitting = ref(false);
const currentPipeData = ref<PipeData | null>(null);
const currentPoints = ref<PipePoint[]>([]);

// 防止重复调用的标志
const isDrawingCompleted = ref(false);

// 存储用户绘制的管线数据
const userDrawnPipe = ref<PipeData | null>(null);
// 存储从接口请求回来的管线数据
const loadedPipes = ref<PipeData[]>([]);
// 存储用户绘制管线的风险数据
const userPipeRiskData = ref<any>(null);

// 使用地图初始化 hook
const {
  viewer: pipeDrawingViewer,
  isInitialized,
  initMap
} = useCesiumMap({
  containerRef: pipeDrawingContainer,
  onMapReady: () => {
    console.log('地图准备就绪');
  }
});

// 使用管线绘制 hook
const { isDrawing, startDrawing, stopDrawing, finishDrawing, undoLastPoint, clearAllPipes, loadPipesFromResponse, addRiskInfoHover } = usePipeDrawing(
  {
    viewer: pipeDrawingViewer,
    onPointAdded: (points: PipePoint[]) => {
      currentPoints.value = points;
    },
    onDrawingComplete: (pipeData: PipeData) => {
      currentPipeData.value = pipeData;
      onDrawingComplete(pipeData);
    },
    getUserDrawnPipe: () => userDrawnPipe.value
  }
);

// Dialog相关
const { visible: dialogVisible, openDialog: openDialogHook, closeDialog: closeDialogHook } = useDialog({ title: '管线绘制工具' });
const emit = defineEmits(['close']);

// 风险模型数据
const riskModel = reactive({
  '接口类型': [],
  '管材': [],
  '管道位置': [],
  '管道压力': [],
  '管道深度': [],
  '管道设计': [],
  '地质': [],
  '施工破坏': [],
  '气象': [],
  '自然灾害': [],
  '在线监测数据': [],
  '监测预警': [],
  '巡检频率': [],
  '泄漏记录': [],
  '维修记录': []
});

// 表单数据
const formData = reactive({
  gj: null,
  gl: null,
  jklx: '',
  gc: '',
  gdwz: '',
  gdyl: '',
  gdsd: null,
  gdsj: '',
  dz: [],
  dzsl: null,
  sgph: '',
  qw: null,
  qx: [],
  zrzh: '',
  zxjcsj: '',
  xjpl: '',
  jcyj: '',
  xljl: '',
  wxjl: ''
});

// 表单验证规则
const formRules = {
  gj: [{ required: true, message: '请输入管径', trigger: 'blur' }],
  gl: [{ required: true, message: '请输入管龄', trigger: 'blur' }]
};

// 判断是否有管线
const hasPipes = computed(() => {
  return currentPipeData.value !== null;
});

// 初始化风险模型数据
const initRiskModelData = async () => {
  const param = [
    '接口类型',
    '管材',
    '管道位置',
    '管道压力',
    '管道深度',
    '管道设计',
    '地质',
    '施工破坏',
    '气象',
    '自然灾害',
    '在线监测数据',
    '监测预警',
    '巡检频率',
    '泄漏记录',
    '维修记录'
  ];

  try {
    for (const item of param) {
      const { data } = await scoringCriteria({ quotaName: item });
      if (data?.tableColumns) {
        const tableColumns = data.tableColumns;
        const arr = [];
        for (let i = 0; i < tableColumns.length; i++) {
          if (i > 0) {
            const tableColumn = tableColumns[i];
            arr.push({ label: tableColumn.label, value: tableColumn.prop });
          }
        }
        riskModel[item] = arr;
      }
    }
    console.log('风险模型数据加载完成:', riskModel);
  } catch (error) {
    console.error('加载风险模型数据失败:', error);
    ElMessage.error('加载风险模型数据失败');
  }
};

// 切换绘制状态
const toggleDrawing = () => {
  try {
    if (isDrawing.value) {
      console.log('取消绘制模式');
      // 取消绘制，清除当前正在绘制的点
      stopDrawing();
      currentPoints.value = [];
      isDrawingCompleted.value = false;
      ElMessage.info('已取消绘制，当前绘制的点已清除');
    } else {
      console.log('开始绘制模式');
      // 开始绘制
      startDrawing();
      isDrawingCompleted.value = false;
      ElMessage.success('开始绘制，请在地图上点击添加管线点，点击完成绘制来结束绘制');
      console.log('绘制模式已启动，可以开始点击地图');
    }
  } catch (error) {
    console.error('切换绘制状态失败:', error);
    ElMessage.error('操作失败，请重试');
  }
};

// 清除地图上的所有管线和距离相关实体
const clearMapEntities = () => {
  const viewer = pipeDrawingViewer.value;
  if (viewer) {
    // 只清除距离相关的实体，管线实体由 clearAllPipes 负责
    const entitiesToRemove: any[] = [];

    // 先收集所有需要删除的实体
    const allEntities = Array.from(viewer.entities.values);

    allEntities.forEach((entity) => {
      if (entity.id && typeof entity.id === 'string') {
        // 只清除距离相关的实体，不清除管线实体
        if (
          entity.id.startsWith('distance_line_') ||
          entity.id.startsWith('distance_start_dot_') ||
          entity.id.startsWith('distance_end_dot_') ||
          entity.id.startsWith('distance_label_')
        ) {
          entitiesToRemove.push(entity);
        }
      }
    });

    // 批量移除距离相关实体
    entitiesToRemove.forEach((entity) => {
      viewer.entities.remove(entity);
    });

    console.log(`已清除 ${entitiesToRemove.length} 个距离相关实体`);
  }
};

// 清除所有管线
const handleClearAllPipes = () => {
  clearMapEntities(); // 清除距离相关实体
  clearAllPipes(); // 清除管线相关实体

  currentPipeData.value = null;
  currentPoints.value = [];
  userDrawnPipe.value = null;
  loadedPipes.value = [];
  userPipeRiskData.value = null; // 清除风险数据
  isDrawingCompleted.value = false;
  ElMessage.success('已清除所有管线和距离连线');
};

// 完成绘制
const handleFinishDrawing = () => {
  if (isDrawing.value) {
    try {
      const result = finishDrawing();
      if (result) {
        onDrawingComplete(result);
      }
    } catch (error) {
      console.error('完成绘制失败:', error);
      ElMessage.error('完成绘制失败，请重试');
    }
  }
};

// 撤销最后一个点
const handleUndoLastPoint = () => {
  if (isDrawing.value) {
    undoLastPoint();
  }
};

// 提交管线数据
const submitPipeData = async () => {
  if (!currentPipeData.value) {
    ElMessage.warning('请先绘制管线');
    return;
  }

  try {
    await formRef.value.validate();

    submitting.value = true;

    // 过滤掉空值并构建提交数据
    const pipeInfo = {};
    Object.entries(formData).forEach(([key, value]) => {
      // 对于数组，检查是否有值
      if (Array.isArray(value)) {
        if (value.length > 0) {
          pipeInfo[key] = value;
        }
      }
      // 对于其他类型，检查是否为空或undefined或null或空字符串
      else if (value !== '' && value !== undefined && value !== null) {
        pipeInfo[key] = value;
      }
    });

    const submitData = {
      pipeInfo,
      pipeGeometry: {
        points: currentPipeData.value.points
      }
    };

    console.log('提交的数据:', submitData);

    // 提交到后端
    const { code, data } = await submitPipeDataApi(submitData);

    // 处理后端返回的数据
    if (code === 200 && data) {
      ElMessage.success('提交成功！');

      // 保存风险数据
      if (data.riskValue && data.riskValue.info) {
        userPipeRiskData.value = data.riskValue.info;
        console.log('风险数据:', userPipeRiskData.value);

        // 为用户管线添加风险信息悬停功能
        if (userDrawnPipe.value) {
          addRiskInfoHover(userDrawnPipe.value, userPipeRiskData.value);
        }
      }

      // 加载其他管线到地图
      if (data.lineData && Array.isArray(data.lineData) && data.lineData.length > 0) {
        await loadPipesFromResponse(data.lineData);
      } else {
        ElMessage.warning('未查询到周边热力管线或轨道交通');
      }
    }
  } catch (error) {
    console.error('提交管线数据失败:', error);
    ElMessage.error('提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 监听绘制完成事件
const onDrawingComplete = (pipeData: PipeData) => {
  // 防止重复调用
  if (isDrawingCompleted.value) {
    return;
  }
  isDrawingCompleted.value = true;
  currentPipeData.value = pipeData;
  isDrawing.value = false;
  currentPoints.value = pipeData.points;

  // 保存用户绘制的管线
  userDrawnPipe.value = pipeData;

  ElMessage.success('管线绘制完成，请填写管线信息并提交');
};

// Dialog相关方法
const closeDialog = () => {
  // 停止绘制并清理状态
  if (isDrawing.value) {
    stopDrawing();
  }

  // 清除所有管线和距离相关实体
  clearMapEntities();

  clearAllPipes();

  // 清理状态
  currentPoints.value = [];
  currentPipeData.value = null;
  userDrawnPipe.value = null;
  loadedPipes.value = [];
  userPipeRiskData.value = null; // 清除风险数据
  isDrawingCompleted.value = false;

  // 不销毁地图，只是隐藏对话框
  closeDialogHook();
  emit('close');
};

// 暴露方法给父组件
const openDialog = async () => {
  openDialogHook();

  // 只在第一次初始化地图
  if (!isInitialized.value) {
    nextTick(() => {
      initMap();
    });
  }

  // 清除之前的管线和距离相关实体
  clearMapEntities();

  clearAllPipes();

  // 重新加载风险模型数据
  await initRiskModelData();

  // 重置表单数据
  Object.assign(formData, {
    gj: null,
    gl: null,
    jklx: '',
    gc: '',
    gdwz: '',
    gdyl: '',
    gdsd: null,
    gdsj: '',
    dz: [],
    dzsl: null,
    sgph: '',
    qw: null,
    qx: [],
    zrzh: '',
    zxjcsj: '',
    xjpl: '',
    jcyj: '',
    xljl: '',
    wxjl: ''
  });
  currentPipeData.value = null;
  currentPoints.value = [];
  userDrawnPipe.value = null;
  loadedPipes.value = [];
  userPipeRiskData.value = null; // 清除风险数据
  isDrawing.value = false;
  isDrawingCompleted.value = false;
};

defineExpose({
  openDialog,
  closeDialog
});
</script>

<style scoped>
.pipe-drawing-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    height: 70vh;
  }
}

.pipe-drawing-container {
  display: flex;
  height: 100%;
  width: 100%;
}

.map-container {
  flex: 1;
  position: relative;
  height: 70vh;
}

.map-container :deep(#cesiumContainer) {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: stretch;
}

.map-legend {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.legend-item:last-child {
  margin-bottom: 0;
}

.legend-color {
  width: 20px;
  height: 4px;
  margin-right: 8px;
  border-radius: 2px;
}

.legend-item span {
  font-size: 12px;
  color: #333;
}

.map-controls .el-button {
  width: 100%;
  justify-content: center;
  margin: 0 !important;
}

.form-container {
  width: 500px;
  height: 100%;
  overflow-y: auto;
  background: #f5f5f5;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-card {
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pipe-form {
  padding: 0;
}

.pipe-form .el-form-item {
  margin-bottom: 20px;
}

.pipe-form .el-form-item:last-child {
  margin-bottom: 0;
}

.form-scrollbar {
  padding-right: 10px;
}

.form-scrollbar :deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

.form-scrollbar :deep(.el-scrollbar__bar.is-vertical) {
  right: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-container {
    width: 450px;
  }
}

@media (max-width: 768px) {
  .pipe-drawing-container {
    flex-direction: column;
  }

  .form-container {
    width: 100%;
    height: 300px;
  }

  .map-container {
    height: calc(100% - 300px);
  }
}
</style>
